# coding: utf-8
from pymongo import MongoClient

class MongoDBDemo:
    def __init__(self):
        self.mc = MongoClient('192.168.43.158', 27017)
        self.db = self.mc['MongoDBDemo']
        self.col = self.db['mongodbDemo']

    def _test_add(self):
        """
        md = MongoDBDemo()
        md._test_add()
        """
        self.col.insert({'name': 'zhangsan'})
        result = self.col.find_one()
        print(result)
        self.col.insert([{'name': 'lisi'}, {'name': 'wangwu'}])
        results = self.col.find()
        print(results)
        for result in results:
            print(result)

    def _test_update(self):
        """
        md = MongoDBDemo()
        md._test_update()
        """
        self.col.update_one({'name': 'lisi'}, {'$set': {'name': 'lisi_'}})
        results = self.col.find()
        for result in results:
            print(result)
        self.col.update_many({'name': 'lisi'}, {'$set': {'name': 'lisi_'}})
        results = self.col.find()
        for result in results:
            print(result)

    def _test_delete(self):
        """
        md = MongoDBDemo()
        md._test_delete()
        """
        self.col.delete_one({'name': 'lisi'})
        results = self.col.find()
        for result in results:
            print(result)
        self.col.delete_many({})
        results = self.col.find()
        for result in results:
            print(result)

    def _test_select(self):
        """
        md = MongoDBDemo()
        md._test_select()
        """
        # 批量产生数据和自定义查询
        for index in range(1000):
            self.col.insert({'_id': index, 'name': 'MongoDB_' + str(index)})
        results = self.col.find({'$where': 'function(){return this._id % 100 == 0;}'}, {'name': 1, '_id': 0})
        for result in results:
            print(result)

    def __del__(self):
        self.mc.close()


if __name__ == '__main__':
    md = MongoDBDemo()
    md._test_select()
